import axios, { AxiosError, AxiosResponse } from 'axios';
import { message } from 'antd';

interface RetryConfig {
  retries: number;
  retryDelay: number;
  retryCondition?: (error: AxiosError) => boolean;
}

const defaultRetryConfig: RetryConfig = {
  retries: 3,
  retryDelay: 1000,
  retryCondition: (error: AxiosError) => {
    return error.code === 'ECONNABORTED' || 
           error.message.includes('Network Error') ||
           error.message.includes('ECONNREFUSED') ||
           (error.response?.status ?? 0) >= 500;
  }
};

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL || '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    
    if (data.code === 0 || data.code === 200) {
      return data.data;
    }
    
    message.error(data.msg || '请求失败');
    return Promise.reject(new Error(data.msg || '请求失败'));
  },
  async (error: AxiosError) => {
    const config = error.config as any;
    
    // 初始化重试次数
    if (config && !config.retryCount) {
      config.retryCount = 0;
    }

    // 检查是否满足重试条件
    if (
      config &&
      config.retryCount < defaultRetryConfig.retries &&
      defaultRetryConfig.retryCondition?.(error)
    ) {
      config.retryCount += 1;

      // 显示重试消息
      message.loading({
        content: `连接失败，正在进行第${config.retryCount}次重试...`,
        duration: defaultRetryConfig.retryDelay / 1000
      });

      // 延迟重试
      await new Promise(resolve => setTimeout(resolve, defaultRetryConfig.retryDelay));
      
      return instance(config);
    }

    // 处理错误消息
    let errorMessage = '请求失败';
    if (error.response) {
      switch (error.response.status) {
        case 400:
          errorMessage = '请求参数错误';
          break;
        case 401:
          errorMessage = '未授权，请重新登录';
          // 清除token并跳转到登录页
          localStorage.removeItem('token');
          window.location.href = '/login';
          break;
        case 403:
          errorMessage = '拒绝访问';
          break;
        case 404:
          errorMessage = '请求的资源不存在';
          break;
        case 500:
          errorMessage = '服务器内部错误';
          break;
        default:
          errorMessage = `请求失败: ${error.response.status}`;
      }
    } else if (error.request) {
      errorMessage = '无法连接到服务器，请检查网络';
    }

    message.error(errorMessage);
    return Promise.reject(error);
  }
);

export const request = {
  get: <T = any>(url: string, config = {}) => instance.get<T>(url, config),
  post: <T = any>(url: string, data = {}, config = {}) => instance.post<T>(url, data, config),
  put: <T = any>(url: string, data = {}, config = {}) => instance.put<T>(url, data, config),
  delete: <T = any>(url: string, config = {}) => instance.delete<T>(url, config),
}; 